package com.heyige.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Redis配置类
 */
@Configuration
@EnableCaching
public class RedisConfig {

    /**
     * 配置CacheManager
     *
     * @param connectionFactory Redis连接工厂
     * @return CacheManager实例
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 默认缓存配置
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30)) // 默认30分钟过期
                .serializeKeysWith(org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair
                        .fromSerializer(RedisSerializer.string()))
                .serializeValuesWith(org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair
                        .fromSerializer(RedisSerializer.json()));

        // 为不同的缓存设置不同的过期时间
        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

        // 用户配额缓存 - 1小时过期
        cacheConfigurations.put("userQuota", defaultCacheConfig.entryTtl(Duration.ofHours(1)));

        // 敏感词缓存 - 2小时过期
        cacheConfigurations.put("sensitiveWords", defaultCacheConfig.entryTtl(Duration.ofHours(2)));

        // AI模型状态缓存 - 5分钟过期
        cacheConfigurations.put("aiModelStatus", defaultCacheConfig.entryTtl(Duration.ofMinutes(5)));

        // 聊天历史缓存 - 1小时过期
        cacheConfigurations.put("chatHistory", defaultCacheConfig.entryTtl(Duration.ofHours(1)));

        // 系统监控缓存 - 1分钟过期
        cacheConfigurations.put("systemMonitor", defaultCacheConfig.entryTtl(Duration.ofMinutes(1)));

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultCacheConfig)
                .withInitialCacheConfigurations(cacheConfigurations)
                .build();
    }

}